package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.byit.domain.AppUser;
import com.byit.enums.PromptInfo;
import com.byit.jwt.ann.JwtUser;
import com.byit.jwt.domain.JwtSession;
import com.byit.msg.MessageResult;
import com.byit.service.IAppUserDeviceService;
import com.byit.service.IAppUserService;
import com.byit.utils.MinioUtil;
import com.byit.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangx
 * @since 2019-01-03
 */
@RestController
@RequestMapping("/app/appUser")
public class AppUserController {

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IAppUserDeviceService appUserDeviceService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MinioUtil minioUtil;

    /**
     * 用户详情
     */
    @GetMapping("/info")
    public Object info(@JwtUser JwtSession session) {
        String token = session.token();
        if (!session.isLogin()) { // 没有登录
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        JSONObject data = appUserService.getUserInfo(userId);
        data.put("token",token);
        return MessageResult.success(data);
    }

    /**
     * 修改昵称
     */
    @PostMapping("/anonymous")
    public Object anonymous(@JwtUser JwtSession session,
                            @RequestParam("anonymous") String anonymous) {

        if (!session.isLogin()) { // 没有登录
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }

        AppUser user = appUserService.selectByAnonymous(anonymous);
        if (null != user) {
            return MessageResult.warpper(PromptInfo.ANONYMOUS_IS_EXISTS);
        }

        appUserService.updateAnonymous(userId, anonymous);

        return MessageResult.warpper("000", null, "修改昵称成功");
    }

    /**
     * 修改个性签名
     */
    @PostMapping("/signature")
    public Object signature(@JwtUser JwtSession session,
                            @RequestParam("signature") String signature) {

        if (!session.isLogin()) { // 没有登录
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }

        appUserService.updateSignature(userId, signature);

        return MessageResult.warpper("000", null, "修改签名成功");
    }

    /**
     * 修改头像
     *
     * @param session
     * @param avatar  头像地址
     * @return
     */
    @PostMapping("/avatar")
    public Object avatar(@JwtUser JwtSession session,
                         @RequestParam("avatar") MultipartFile avatar) {

        if (!session.isLogin()) { // 没有登录
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        //头像
        JSONObject flg = null;
        try {
            flg = minioUtil.uploadFile(avatar.getInputStream(),
                    avatar.getOriginalFilename().substring(avatar.getOriginalFilename().lastIndexOf(".")), "appUser/");
            if ("1".equals(flg.getString("flag"))) {
                return MessageResult.warpper(PromptInfo.ERROR_AVATAR_UPLOAD);
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("avatar", flg.getString("path"));
                map.put("id", userId);
                map.put("modifyTime", new Date());
                appUserService.updateAvatar(map);
                return MessageResult.warpper("000", map, "修改头像成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MessageResult.warpper("000", null, "修改头像失败");
    }

    /**
     * 修改手机号-验证原手机
     *
     * @param session
     * @param code    验证码
     * @return
     */
    @PostMapping("/mobile/old")
    public Object mobileOld(@JwtUser JwtSession session,
                            @RequestParam("code") String code) {

        if (!session.isLogin()) { // 没有登录
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        AppUser user = appUserService.selectById(userId);
        String key = "system:sjyzm:5:" + user.getPhone();
        if (!redisUtil.hasKey(key)) {
            return MessageResult.warpper(PromptInfo.ERROR_SMS_CODE_NOT_EXISTS);
        }
        if (null != code && !"".equals(code.trim()) && code.equals(redisUtil.get(key))) {
            return MessageResult.success();
        }
        return MessageResult.warpper(PromptInfo.VERIFY_CODE_ERROR);
    }

    /**
     * 修改手机号-验证新手机
     *
     * @param session
     * @param code    验证码
     * @param mobile  新手机号
     * @return
     */
    @PostMapping("/mobile/new")
    public Object mobileNew(@JwtUser JwtSession session,
                            @RequestParam("code") String code,
                            @RequestParam("mobile") String mobile) {

        if (!session.isLogin()) { // 没有登录
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }

        if (mobile.length() != 11) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_LOGIN_PHONE);
        }

        String key = "system:sjyzm:5:" + mobile;
        if (!redisUtil.hasKey(key)) {
            return MessageResult.warpper(PromptInfo.ERROR_SMS_CODE_NOT_EXISTS);
        }
        if (null != code && !"".equals(code.trim()) && code.equals(redisUtil.get(key))) {

            AppUser user = appUserService.selectByPhone(mobile);
            if (null != user) {
                return MessageResult.warpper(PromptInfo.USER_IS_EXISTS);
            }

            Map<String, Object> map = new HashMap<>();
            map.put("mobile", mobile);
            map.put("id", userId);
            map.put("modifyTime", new Date());
            appUserService.updateMobile(map);
            return MessageResult.success();
        }
        return MessageResult.warpper(PromptInfo.VERIFY_CODE_ERROR);
    }


    /**
     * 账户状态变更
     *
     * @param session
     * @return
     */
    @PostMapping("/statue/change")
    public Object delete(@JwtUser JwtSession session,
                         @RequestParam("type") Integer type) {

        if (!session.isLogin()) { // 没有登录
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", userId);
        map.put("modifyTime", new Date());
        if (type == 1) {//注销
            appUserService.updateDelete(map);
            return MessageResult.warpper("000", null, "注销成功");
        } else if (type == 2) {//挂失
            appUserService.updateLoss(map);
            return MessageResult.warpper("000", null, "挂失成功");
        } else if (type == 3) {//解冻
            appUserService.updateRestore(map);
            return MessageResult.warpper("000", null, "解冻成功");
        }
        return MessageResult.error();
    }


    /**
     * 查询登录历史设备
     *
     * @param session
     * @return
     */
    @GetMapping("/device/history")
    public Object deviceHistory(@JwtUser JwtSession session) {

        if (!session.isLogin()) { // 没有登录
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.warpper(PromptInfo.NOT_LOGGED);
        }
        List<JSONObject> list = appUserDeviceService.selectByUserId(userId);
        return MessageResult.success(list);
    }


}
